/**
 * @param {string[]} matrix
 * @param {number[]} start
 * @param {number[]} end
 * @return {number}
 */
 var conveyorBelt = function(matrix, start, end) {
  const DIR = {
    '^': [-1,0],
    'v': [1,0],
    '<': [0,-1],
    '>': [0,1]
  }
  const DIR1 = {
    '^': [1,0],
    'v': [-1,0],
    '<': [0,1],
    '>': [0,-1]
  }
  const m = matrix.length, n = matrix[0].length
  let [x, y] = start
  const [e1, e2] = end
  const used = new Set()
  const arr = new Array(m).fill(0).map(() => new Array(n).fill(-1))
  let flag = true
  while(x !== e1 && y !== e2) {
    let z = matrix[x][y]
    const [dx, dy] = DIR[z]
    let x1 = x+dx, y1 = y+dy
    used.add(`${x}-${y}`)
    arr[x][y] = [...start]
    if(x1 >= 0 && x1 < m && y1 >= 0 && y1 < n && !used.has(`${x1}-${y1}`)) {
      x = x1
      y = y1
    }else {
      flag = false
      break
    }
  }
  if(flag) {
    return 0
  }
  let q = []
  arr[e1][e2] = [e1, e2]
  for(const [x, y, z] of [[e1-1, e2, 0], [e1+1, e2, 1], [e1, e2-1, 2], [e1, e2+1, 3]]) {
    if(x >= 0 && x < m && y >= 0 && y < n) {
      let o1 = matrix[x][y]
      let [dx1, dy1] = DIR[o1]
      if(x + dx1 === e1 && y + dy1 === e2) {
        q.push([x, y, z])
      } 
    }
  }
  used.clear()
  while(q.length) {
    let t = []
    for(const [x, y, z] of q) {
      arr[x][y] = [e1, e2, z]
      used.add(`${x}-${y}`)
      let o = matrix[x][y]
      const [dx, dy] = DIR1[o]
      let x1 = x+dx, y1 = y+dy
      if(x1 >= 0 && x1 < m && y1 >= 0 && y1 < n && !used.has(`${x1}-${y1}`)) {
        let o1 = matrix[x1][y1]
        let [dx1, dy1] = DIR[o1]
        if(x1 + dx1 === x && y1 + dy1 === y) {
          t.push([x1, y1, z])
        }
      }
    }
    q = t
  }
  let a = [], b = new Array(4).fill([])
  for(let i = 0; i<m; i++) {
    for(let j = 0; j<n; j++) {
      if(arr[i][j] === -1) continue
      if(arr[i][j][0] === start[0] && arr[i][j][1] === start[1]) {
        a.push([i, j])
      }
      if(arr[i][j].length === 2) continue
      if(arr[i][j][0] === e1 && arr[i][j][1] === e2) {
        let z = arr[i][j][2]
        b[z].push([i, j])
      }
    }
  }
  let ans = Infinity
  for(const [x1, y1] of a) {
    ans = Math.min(Math.abs(x1-e1) + Math.abs(y1-e2), ans)
  }
  for(let i = 0; i<4; i++) {
    for(const [x2, y2] of b[i]) {
      for(const [x1, y1] of a) {
        ans = Math.min(Math.abs(x1-x2) + Math.abs(y1-y2), ans)
      }
    }
  }
  return ans
};